package cn.stronglink.esm27.collection.iot.devices.esm27.request.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.stronglink.esm27.collection.core.message.IMessageHandle;
import cn.stronglink.esm27.collection.core.util.ContextUtils;
import cn.stronglink.esm27.collection.iot.devices.esm27.ESM27Server;
import cn.stronglink.esm27.collection.iot.devices.esm27.message.MQMessageOfESM27;
import cn.stronglink.esm27.collection.iot.devices.esm27.request.entity.OpenSerialPortEntity;
import cn.stronglink.esm27.collection.iot.devices.esm27.task.AutoPushSensorDataTask;
import cn.stronglink.esm27.collection.mq.TopicSender;
import io.netty.channel.ChannelHandlerContext;

public class OpenSerialPortHandle implements IMessageHandle<MQMessageOfESM27, Object> {
	private static Logger logger = LogManager.getLogger(OpenSerialPortHandle.class.getName());
	private final static String ACTION_CODE = "OpenSerialPort"; // MQ中判断消息类型的标识符
	private final static String ACTION_CODE_RETURN = "OpenSerialPortReturn"; // MQ中判断消息类型的标识符
	private ESM27Server esm27Server=(ESM27Server) ContextUtils.getBean("esm27Server"); // esm27服务器
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	protected AutoPushSensorDataTask autoPushSensorDataTask = (AutoPushSensorDataTask)ContextUtils.getBean("autoPushSensorDataTask");
	@Override
	public boolean isHandle(MQMessageOfESM27 t) {
		if (t.getActioncode().equals(ACTION_CODE)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, MQMessageOfESM27 t) {
		try {
			OpenSerialPortEntity sp = ((JSONObject)t.getAwsPostdata()).toJavaObject(OpenSerialPortEntity.class);
			// 打开串口
			esm27Server.setSerialPortName(sp.getSerialPortName());
			esm27Server.openSerialPort();
			logger.info("串口服务已打开，串口号:{}",sp.getSerialPortName());
			
			// 修改定时推送传感器的时间间隔
			int intervalTime = sp.getAutoPushSensorDataIntervalSeconds();
			autoPushSensorDataTask.setCron(this.time2Cron(intervalTime));
			
			this.sendSuccessMessage();
		} catch (Exception e) {
			logger.error(e);
			this.sendExceptionMessage(e);
		}
		return null;
	}
	
	/**
	 * 时间转定时规则字符串
	 * @param time 需要定时执行的秒数
	 * @return
	 */
	private String time2Cron(int time) {
		time=Math.max(time, 30); // 最小30秒
		int minute = time/60;
		int seconds = time % 60;
		String cron = "0/" +seconds + " 0/"+minute+ " * * * ?";
		cron = cron.replace("0/0", "*");
		return cron;
	}

	/**
	 * 发送异常信息到MQ
	 * @param e
	 */
	private void sendSuccessMessage() {
		MQMessageOfESM27 message = new MQMessageOfESM27();
		message.setActioncode(ACTION_CODE_RETURN);
		message.setTimeStamp(System.currentTimeMillis());
		message.setAwsPostdata(null);
		message.setIsSuccess(true);
		
		String json = JSON.toJSONString(message);
		topicSender.send(json);
		logger.info("发送[{}]到MQ完成:{}","打开串口成功反馈信息",json);
	}
	
	/**
	 * 发送异常信息到MQ
	 * @param e
	 */
	private void sendExceptionMessage(Exception e) {
		MQMessageOfESM27 message = new MQMessageOfESM27();
		message.setActioncode(ACTION_CODE_RETURN);
		message.setTimeStamp(System.currentTimeMillis());
		message.setAwsPostdata(null);
		message.setIsSuccess(false);
		message.setErrorMessage(e.getMessage());
		
		String json = JSON.toJSONString(message);
		topicSender.send(json);
		logger.info("发送[{}]到MQ完成:{}","打开串口的异常反馈信息",json);
	}
}
